#include "EpilChunkParser.h"
#include "EpilStatementParser.h"
#include "EpilParser.h"
#include "EpilParserUtilities.h"
#include "EpilPointerHelper.h"


EpilChunkParser::EpilChunkParser( EpilTokenStream & tokens )
: EpilSyntaxParserBase( tokens )
, m_chunk( NULL )
{
}


void EpilChunkParser::Parse()
{
	// chunk -> { stat [`;'] }

	m_chunk = new EpilChunkCode( this->GetTokens().GetCurrentToken().location );

	bool isLast = false;
	while( ! isLast && ! EpilParserUtilities::IsBlockFollow( this->GetTokens() ) )
	{
		EpilStatementParser statParser( this->GetTokens() );
		try
		{
			statParser.Parse();
		}
		catch( ... )
		{
			EpilPointerHelper::SafeDelete( m_chunk );
			throw;
		}
		isLast = statParser.IsLastStatement();
		m_chunk->GetStatements().push_back( statParser.GetStatementCode() );

		if( this->GetTokens().GetCurrentToken().type == ETT_OpSemicolon )
		{
			this->GetTokens().MoveToNext();
		}
	}
}